import re
import project, svn
from datetime import *
import _pg



class PickProject(project.Project):
    def getDatabase(self):
        """Return a pygresql db object based on database info in the project config file"""
        try:
            db = _pg.connect(dbname=self['dbName'], host=self['dbHost'], passwd=self['dbPass'], user=self['dbUser'])
        except KeyError:
            raise project.ProjectError("Error! Project file does not have entries for dbName, dbHost, dbPass and dbUser")
        return db

    def getSVNRepository(self):
        return svn.SVNRepository(self.projectDir + self.getSVNDir())

    def getSVNDir(self):
        try:
            svnDir = self['svnDir']
        except KeyError:
            raise project.ProjectError("svnDir not defined in project file")
        return svnDir

    def getSVNLogPath(self):
        return self.projectDir + "svnlog"

    #Override Project methods so this information is published to the database
    def enterState(self, statename, starttimestamp, endtimestamp, notes):
        project.Project.enterState(self, statename, starttimestamp, endtimestamp, notes)
        self.putStatesInDB()

    def exitState(self, statename):
        project.Project.exitState(self, statename)
        self.putStatesInDB()

    def putStatesInDB(self):
        """Mirrors the state information in <projectname>.project into the db table State"""
        db = self.getDatabase()
        try:
            db.query("drop table state")
        except:
            pass
        db.query("""create table State( 
name varchar(512) NOT NULL, 
starttime timestamp(2) NOT NULL,
endtime timestamp(2) NOT NULL,
notes varchar(512), PRIMARY KEY (name));""")
        for k, v in self["states"].items():
            q = "insert into State values('%s', '%s', '%s', '%s')" % (k, v["starttime"], v["endtime"], v["notes"])
            db.query(q)
        
